package com.pdd.mall.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdd.mall.entity.Merchant;
import com.pdd.mall.mapper.MerchantMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 商家UserDetailsService实现类
 */
@Service("merchantDetailsService")
public class MerchantDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 直接从数据库获取商家信息，避免循环依赖
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Merchant merchant = merchantMapper.selectOne(queryWrapper);

        if (merchant == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        // 商家权限列表
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_MERCHANT"));

        // 返回UserDetails实现类
        return new org.springframework.security.core.userdetails.User(
                merchant.getUsername(),
                merchant.getPassword(),
                merchant.getStatus() == 1, // 账号是否可用
                true, // 账号是否过期
                true, // 密码是否过期
                true, // 账号是否锁定
                authorities
        );
    }
}
